package com.rjpacket.chileme.app.utils;

/**
 * Created by Mmz on 2015/2/5.
 */

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Set;

/**
 * HTTP网络请求的工具类，包含了Get,Post,Put,Delete
 * 这四个请求方法的支持
 */

public class HttpTool {

    //TODO Get请求

    /**
     * 执行Get请求
     *
     * @param url 请求的网址
     * @return byte[] 网络数据
     */
    public static byte[] get(String url) {
        byte[] ret = null;

        if (url != null) {
            HttpGet request = new HttpGet(url);

            //setEntity用于设置提交的数据
            //对于key = value&key = value 的形式，需要使用UrlEncodedFormEntity
            HttpClient client = new DefaultHttpClient();
            client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
            try {
                HttpResponse response = client.execute(request);
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    ret = EntityUtils.toByteArray(entity);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    //TODO Delete请求

    /**
     * Http Delete 请求
     *
     * @param url
     * @return
     */
    public static byte[] delete(String url) {
        byte[] ret = null;

        if (url != null) {
            HttpDelete request = new HttpDelete(url);
            HttpClient client = new DefaultHttpClient();
            try {
                HttpResponse response = client.execute(request);
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    HttpEntity entity = response.getEntity();
                    ret = EntityUtils.toByteArray(entity);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }


    /**
     * 执行POST请求
     * POST请求要提交数据，
     * 提交的方式本方法采用 key = value&key = value的形式
     * 这种数据格式就是网页中，form表单提交的数据格式
     *
     * @param url    请求网址
     * @param params HashMap包含的参数，也就是key = value的集合
     * @return
     */
    public static byte[] post(String url, HashMap<String, String> params) {
        return post(url, params, "UTF-8");
    }

    public static byte[] post(String url, HashMap<String, String> params, String encoding) {

        byte[] ret = null;

        if (url != null) {
            HttpPost request = new HttpPost();
            //setEntity用于设置提交的数据
            //对于key = value&key = value 的形式，需要使用UrlEncodedFormEntity

            ret = processEntityRequest(request, params, encoding);
        }
        return ret;
    }

    /**
     * @param url
     * @param params
     * @param encoding
     * @return
     */
    public static byte[] put(String url, HashMap<String, String> params, String encoding) {

        byte[] ret = null;

        if (url != null) {

            HttpPut request = new HttpPut(url);

            ret = processEntityRequest(request, params, encoding);

        }
        return ret;
    }

    /**
     * 本方法实现了POST请求和PUT请求，发送key=value形式参数的通用代码
     *
     * @param request
     * @param params
     * @param encoding
     * @return
     */
    private static byte[] processEntityRequest(
            HttpEntityEnclosingRequestBase request,
            HashMap<String, String> params,
            String encoding) {

        byte[] ret = null;
        if (request != null) {
            if (params != null) {
                try {
                    LinkedList<NameValuePair> parameters = new LinkedList<NameValuePair>();
                    //TODO 添加参数
                    Set<String> keySet = params.keySet();//获取HashMap里面的key集合

                    for (String key : keySet) {
                        String value = params.get(key);
                        parameters.add(new BasicNameValuePair(key, value));
                    }

                    //将parameters中的key-value通过UrlEncodeFormEntity进行组合
                    //形成key-value&key-value的形式（这种形式是服务器标准数据提交的格式）
                    //为了防止乱码，必须使用两个参数的形式
                    if (encoding == null) {
                        encoding = "UTF-8";
                    }
                    //setEntity用于设置提交的数据
                    //对于key = value&key = value 的形式，需要使用UrlEncodedFormEntity
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, encoding);
                    request.setEntity(entity);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            HttpClient client = new DefaultHttpClient();
            try {
                HttpResponse response = client.execute(request);
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    ret = EntityUtils.toByteArray(entity);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }
}
